import { ConfigProvider, Modal, ModalProps } from 'antd';
import {
  CSSProperties,
  forwardRef,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';

export interface TemplateModalProps extends ModalProps {
  ModalStyles?: CSSProperties;
  children?: any;
  handleOk?: any;
  handleCancel?: any;
}

const Index = forwardRef((props: TemplateModalProps, ref) => {
  const {
    ModalStyles,
    children,
    handleOk = () => {},
    handleCancel = () => {},
    ...rest
  } = props;
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const hideModal = () => {
    setIsModalOpen(false);
  };

  useImperativeHandle(ref, () => ({
    showModal: () => {
      showModal();
    },
    hideModal: () => {
      hideModal();
    },
  }));

  return (
    <ConfigProvider
      modal={{
        styles: {
          ...ModalStyles,
        } as any,
      }}
    >
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={hideModal}
        {...rest}
      >
        {children}
      </Modal>
    </ConfigProvider>
  );
});

export const useTeplateModal = () => {
  const modalRef = useRef<any>(null);
  const showModal = (callBack?: () => void) => {
    callBack && typeof callBack === 'function' && callBack?.();
    modalRef.current?.showModal();
  };
  const hideModal = (callBack?: () => void) => {
    callBack && typeof callBack === 'function' && callBack?.();
    modalRef.current?.hideModal();
  };
  return {
    showModal,
    hideModal,
    modalRef,
    TemplateModal: (props?: TemplateModalProps) => (
      <Index ref={modalRef} {...props}>
        {props?.children}
      </Index>
    ),
  };
};

export default Index;
